// 选手管理模块
class PlayerManager {
    constructor() {
        this.players = [];
        this.loadPlayers();
        this.bindEvents();
        this.updatePlayerList();
    }

    // 从localStorage加载选手数据
    loadPlayers() {
        const savedPlayers = localStorage.getItem('players');
        this.players = savedPlayers ? JSON.parse(savedPlayers) : [];
    }

    // 保存选手数据到localStorage
    savePlayers() {
        localStorage.setItem('players', JSON.stringify(this.players));
    }

    // 添加新选手
    addPlayer(name, initialScore = '0') {
        const player = {
            id: Date.now().toString(),
            name: name,
            score: parseFloat(initialScore) || 0,
            gamesPlayed: 0
        };
        this.players.push(player);
        this.savePlayers();
        this.updatePlayerList();
    }

    // 更新选手列表显示
    updatePlayerList() {
        const tbody = document.querySelector('.card-table .table-vcenter tbody');
        if (!tbody) return;
        
        if (this.players.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-muted">暂无选手信息</td></tr>';
            return;
        }

        // 按积分降序排序
        const sortedPlayers = [...this.players].sort((a, b) => b.score - a.score);

        // 计算总积分
        const totalScore = this.players.reduce((sum, player) => sum + (player.score || 0), 0);

        tbody.innerHTML = sortedPlayers.map(player => {
            // 计算积分百分比
            const scorePercentage = totalScore > 0 ? (player.score / totalScore * 100).toFixed(1) : 0;
            
            return `
                <tr>
                    <td>${player.name}</td>
                    <td>${(player.score || 0).toFixed(1)}</td>
                    <td>${player.gamesPlayed || 0}</td>
                    <td class="w-50">
                        <div class="progress progress-xs">
                            <div class="progress-bar bg-primary" style="width: ${scorePercentage}%"></div>
                        </div>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-danger delete-player" data-id="${player.id}">
                            删除
                        </button>
                    </td>
                </tr>
            `;
        }).join('');

        // 强制触发DOM更新
        tbody.style.display = 'none';
        setTimeout(() => tbody.style.display = '', 0);
    }

    // 绑定事件处理
    deletePlayer(id) {
        if (confirm('确定要删除这个选手吗？')) {
            this.players = this.players.filter(p => p.id !== id);
            this.savePlayers();
            this.updatePlayerList();
        }
    }

    // 导出选手数据到文件
    exportPlayers() {
        const data = JSON.stringify(this.players, null, 2);
        const blob = new Blob([data], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'players.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 导入选手数据
    importPlayers(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const data = JSON.parse(e.target.result);
                    this.players = data;
                    this.savePlayers();
                    this.updatePlayerList();
                    resolve();
                } catch (error) {
                    reject('文件格式错误');
                }
            };
            reader.onerror = () => reject('读取文件失败');
            reader.readAsText(file);
        });
    }

    bindEvents() {
        const addPlayerForm = document.querySelector('#modal-pepol');
        if (!addPlayerForm) return;

        // 添加导入导出按钮到表格标题栏
        const cardHeader = document.querySelector('.card-header');
        if (cardHeader) {
            const buttonGroup = document.createElement('div');
            buttonGroup.className = 'btn-group float-end';
            buttonGroup.innerHTML = `
                <button class="btn btn-sm btn-primary export-players">导出数据</button>
                <label class="btn btn-sm btn-success import-players">
                    导入数据
                    <input type="file" accept=".json" style="display: none;">
                </label>
            `;
            cardHeader.appendChild(buttonGroup);

            // 绑定导出按钮事件
            const exportBtn = cardHeader.querySelector('.export-players');
            exportBtn.addEventListener('click', () => this.exportPlayers());

            // 绑定导入按钮事件
            const importInput = cardHeader.querySelector('input[type="file"]');
            importInput.addEventListener('change', async (e) => {
                const file = e.target.files[0];
                if (file) {
                    try {
                        await this.importPlayers(file);
                        alert('数据导入成功');
                    } catch (error) {
                        alert(error);
                    }
                    importInput.value = '';
                }
            });
        }

        // 绑定删除选手事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('delete-player')) {
                const playerId = e.target.dataset.id;
                this.deletePlayer(playerId);
            }
        });

        // 初始化Bootstrap模态框
        const modal = new bootstrap.Modal(addPlayerForm, {
            backdrop: 'static',
            keyboard: false
        });

        // 当模态框显示时，聚焦到姓名输入框
        addPlayerForm.addEventListener('shown.bs.modal', () => {
            const nameInput = addPlayerForm.querySelector('input[name="name"]');
            if (nameInput) nameInput.focus();
        });

        // 监听模态框隐藏事件
        addPlayerForm.addEventListener('hidden.bs.modal', () => {
            const nameInput = addPlayerForm.querySelector('input[name="name"]');
            const scoreInput = addPlayerForm.querySelector('input[name="score"]');
            if (nameInput) nameInput.value = '';
            if (scoreInput) scoreInput.value = '';
        });

        // 添加关闭按钮事件监听
        const closeButtons = addPlayerForm.querySelectorAll('[data-bs-dismiss="modal"]');
        closeButtons.forEach(button => {
            button.addEventListener('click', () => {
                modal.hide();
            });
        });

        // 保存选手信息
        const savePlayerBtn = addPlayerForm.querySelector('.btn-primary');
        if (savePlayerBtn) {
            savePlayerBtn.addEventListener('click', () => {
                const nameInput = addPlayerForm.querySelector('input[name="name"]');
                const scoreInput = addPlayerForm.querySelector('input[name="score"]');
                
                if (!nameInput || !scoreInput) return;
                
                const name = nameInput.value.trim();
                const score = scoreInput.value.trim();

                if (name && score && !isNaN(parseFloat(score))) {
                    this.addPlayer(name, score);
                    
                    // 重置表单
                    nameInput.value = '';
                    scoreInput.value = '0';
                    
                    // 使用Bootstrap的modal方法关闭对话框
                    modal.hide();
                }
            });
        }
    }

    // 获取所有选手
    getAllPlayers() {
        return this.players;
    }

    // 更新选手积分
    updatePlayerScores(winner, loser, nonParticipants) {
        // 胜者+1分
        const winnerPlayer = this.players.find(p => p.id === winner);
        const loserPlayer = this.players.find(p => p.id === loser);
        
        if (winnerPlayer) {
            winnerPlayer.score += 1;
            winnerPlayer.gamesPlayed += 1;
        }
        
        if (loserPlayer) {
            loserPlayer.score -= 1;
            loserPlayer.gamesPlayed += 1;
        }

        // 未参与者+0.5分
        nonParticipants.forEach(id => {
            const player = this.players.find(p => p.id === id);
            if (player) {
                player.score += 0.5;
            }
        });

        // 保存更新后的数据
        this.savePlayers();
        this.updatePlayerList();
    }
}

// 初始化选手管理器
const playerManager = new PlayerManager();